package com.wstuo.common.security.action;

import com.opensymphony.xwork2.ActionSupport;

import com.wstuo.common.dto.PageDTO;
import com.wstuo.common.exception.ApplicationException;
import com.wstuo.common.security.dto.CompanyDTO;
import com.wstuo.common.security.dto.OrganizationDTO;
import com.wstuo.common.security.dto.OrganizationQueryDTO;
import com.wstuo.common.security.dto.OrganizationTreeDTO;
import com.wstuo.common.security.service.ICompanyService;
import com.wstuo.common.security.service.ICustomerService;
import com.wstuo.common.security.service.IOrganizationInnerService;
import com.wstuo.common.security.service.IOrganizationService;
import com.wstuo.common.security.service.IOrganizationServicesService;
import com.wstuo.common.security.service.ISupplierService;
import com.wstuo.common.security.utils.AppConfigUtils;
import com.wstuo.common.security.utils.AppContext;

import java.io.File;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

/**
 * 机构管理Action类
 * 
 * @author QXY
 */
@SuppressWarnings("serial")
public class OrganizationAction extends ActionSupport {
	@Autowired
	private IOrganizationService organizationService;
	@Autowired
	private ICompanyService companyService;
	@Autowired
	private ICustomerService customerService;
	@Autowired
	private ISupplierService supplierService;
	@Autowired
	private IOrganizationInnerService organizationInnerService;
	@Autowired
	private AppContext appctx;
	private OrganizationDTO organizationDto = new OrganizationDTO();
	private OrganizationQueryDTO organizationQueryDto = new OrganizationQueryDTO();
	private OrganizationTreeDTO organizations;
	private CompanyDTO company = new CompanyDTO();
	private String orgTypeString;
	private int page = 1;
	private int rows = 20;
	private PageDTO organizationPage;
	private Long[] orgNos;
	private String actionType;
	private String doTag;
	private Long orgNo;
	private String orgType;
	private List<Long> orgRoles;
	private InputStream imageStream;
	private File importFile;
	private InputStream exportFile;
	private String effect;
	private String imgFilePath;
	private Long companyNo;
	private String msg;

	private String sidx;
	private String sord;

	private String orgTypes[];
	private Long parentOrgNo;
	private List<OrganizationTreeDTO> orgTreeDtoList;

	public String getImgFilePath() {
		return imgFilePath;
	}

	public void setImgFilePath(String imgFilePath) {
		this.imgFilePath = imgFilePath;
	}

	public String[] getOrgTypes() {
		return orgTypes;
	}

	public void setOrgTypes(String[] orgTypes) {
		this.orgTypes = orgTypes;
	}

	public InputStream getImageStream() {
		return imageStream;
	}

	public void setImageStream(InputStream imageStream) {
		this.imageStream = imageStream;
	}

	public String getSidx() {
		return sidx;
	}

	public void setSidx(String sidx) {
		this.sidx = sidx;
	}

	public String getSord() {
		return sord;
	}

	public void setSord(String sord) {
		this.sord = sord;
	}

	public String getEffect() {
		return effect;
	}

	public void setEffect(String effect) {
		this.effect = effect;
	}

	public File getImportFile() {
		return importFile;
	}

	public void setImportFile(File importFile) {
		this.importFile = importFile;
	}

	public InputStream getExportFile() {
		return exportFile;
	}

	public void setExportFile(InputStream exportFile) {
		this.exportFile = exportFile;
	}

	public List<Long> getOrgRoles() {
		return orgRoles;
	}

	public void setOrgRoles(List<Long> orgRoles) {
		this.orgRoles = orgRoles;
	}

	private List<OrganizationDTO> orgList = new ArrayList<OrganizationDTO>();

	public List<OrganizationDTO> getOrgList() {
		return orgList;
	}

	public void setOrgList(List<OrganizationDTO> orgList) {
		this.orgList = orgList;
	}

	private IOrganizationServicesService organizationServicesService;

	public CompanyDTO getCompany() {
		return company;
	}

	public void setCompany(CompanyDTO company) {
		this.company = company;
	}

	public String getOrgType() {
		return orgType;
	}

	public void setOrgType(String orgType) {
		this.orgType = orgType;
	}

	public Long getOrgNo() {
		return orgNo;
	}

	public void setOrgNo(Long orgNo) {
		this.orgNo = orgNo;
	}

	public IOrganizationInnerService getOrganizationInnerService() {
		return organizationInnerService;
	}

	public void setOrganizationInnerService(IOrganizationInnerService organizationInnerService) {
		this.organizationInnerService = organizationInnerService;
	}

	public ICustomerService getCustomerService() {
		return customerService;
	}

	public void setCustomerService(ICustomerService customerService) {
		this.customerService = customerService;
	}

	public ISupplierService getSupplierService() {
		return supplierService;
	}

	public void setSupplierService(ISupplierService supplierService) {
		this.supplierService = supplierService;
	}

	public String getDoTag() {
		return doTag;
	}

	public void setDoTag(String doTag) {
		this.doTag = doTag;
	}

	public String getActionType() {
		return actionType;
	}

	public void setActionType(String actionType) {
		this.actionType = actionType;
	}

	public Long[] getOrgNos() {
		return orgNos;
	}

	public void setOrgNos(Long[] orgNos) {
		this.orgNos = orgNos;
	}

	public OrganizationQueryDTO getOrganizationQueryDto() {
		return organizationQueryDto;
	}

	public void setOrganizationQueryDto(OrganizationQueryDTO organizationQueryDto) {
		this.organizationQueryDto = organizationQueryDto;
	}

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public int getRows() {
		return rows;
	}

	public void setRows(int rows) {
		this.rows = rows;
	}

	public PageDTO getOrganizationPage() {
		return organizationPage;
	}

	public void setOrganizationPage(PageDTO organizationPage) {
		this.organizationPage = organizationPage;
	}

	public ICompanyService getCompanyService() {
		return companyService;
	}

	public void setCompanyService(ICompanyService companyService) {
		this.companyService = companyService;
	}

	public OrganizationTreeDTO getOrganizations() {
		return organizations;
	}

	public List<OrganizationTreeDTO> getOrgTreeDtoList() {
		return orgTreeDtoList;
	}

	public void setOrgTreeDtoList(List<OrganizationTreeDTO> orgTreeDtoList) {
		this.orgTreeDtoList = orgTreeDtoList;
	}

	/**
	 * set method for OrganizationTreeDTO.
	 * 
	 * @param organizations
	 *            OrganizationTreeDTO
	 */
	public void setOrganizations(OrganizationTreeDTO organizations) {
		this.organizations = organizations;
	}

	/**
	 * get method for OrganizationDTO.
	 * 
	 * @return OrganizationDTO
	 */
	public OrganizationDTO getOrganizationDto() {
		return organizationDto;
	}

	/**
	 * set method for OrganizationDTO.
	 * 
	 * @param organizationDto
	 *            OrganizationDTO
	 */
	public void setOrganizationDto(OrganizationDTO organizationDto) {
		this.organizationDto = organizationDto;
	}

	/**
	 * get method for IOrganizationService.
	 * 
	 * @return IOrganizationService
	 */
	public IOrganizationService getOrganizationService() {
		return organizationService;
	}

	/**
	 * get method for IOrganizationService.
	 * 
	 * @param organizationService
	 *            IOrganizationService
	 */
	public void setOrganizationService(IOrganizationService organizationService) {
		this.organizationService = organizationService;
	}

	public String getOrgTypeString() {
		return orgTypeString;
	}

	public void setOrgTypeString(String orgTypeString) {
		this.orgTypeString = orgTypeString;
	}

	public IOrganizationServicesService getOrganizationServicesService() {
		return organizationServicesService;
	}

	public void setOrganizationServicesService(IOrganizationServicesService organizationServicesService) {
		this.organizationServicesService = organizationServicesService;
	}

	public Long getCompanyNo() {
		return companyNo;
	}

	public void setCompanyNo(Long companyNo) {
		this.companyNo = companyNo;
	}

	public Long getParentOrgNo() {
		return parentOrgNo;
	}

	public void setParentOrgNo(Long parentOrgNo) {
		this.parentOrgNo = parentOrgNo;
	}
	
	public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    /**
	 * 查找公司信息.
	 * 
	 * @return String
	 */
	public String findCompany() {
		company = new CompanyDTO();
		company = companyService.findCompany(companyNo);

		return "company";
	}

	/**
	 * 公司LOGO
	 * 
	 * @return inputStream
	 */
	public String findImage() {
		imageStream = companyService.getImageStream(company.getOrgNo());
		return "imageStream";
	}

	public String findImageUrl() {
		imgFilePath = AppConfigUtils.getInstance().getImagePath() + "/";
		return "imgFilePath";
	}
	/**
	 * 根据上传图片名称根据上传的图片取图片
	 * @return
	 */
	public String getImageUrlforimageStream() {
		imageStream = companyService.getImageUrlforimageStream(imgFilePath);
		return "imageStream";
	}
	/**
	 * 根据上传图片名称根据上传的图片取图片
	 * @return
	 */
	public String getapporUserStream() {
		imageStream = organizationService.getImageUrlforimageStream(actionType);
		return "imageStream";
	}
	/**
	 * 查找机构列表.
	 * 
	 * @return String
	 */
	public String find() {
		int start = (page - 1) * rows;
		organizationQueryDto.setSidx(sidx);
		organizationQueryDto.setSord(sord);
		if (companyNo != null) {
			organizationQueryDto.setCompanyNo(companyNo);
		}

		organizationQueryDto.setStart(start);
		organizationQueryDto.setLimit(rows);
		organizationPage = organizationService.findPagerOrganization(organizationQueryDto);
		organizationPage.setPage(page);
		organizationPage.setRows(rows);

		return "organizationPage";
	}

	/**
	 * 查找机构（树结构）
	 * 
	 * @return String result
	 */
	public String findAll() {
		if (parentOrgNo == null || parentOrgNo == 0) {
			orgTreeDtoList = organizationService.findOrgTreeDtos(companyNo);
			return "orgTreeDtoList";
		} else {
			orgTreeDtoList = organizationService.findSubOrgTreeDtos(parentOrgNo);
			return "orgTreeDtoList";
		}
	}
	/**
	 * 查找登陆用户负责的机构（树结构）
	 * 
	 * @return String result
	 */
	public String findAllByUser(){
		orgTreeDtoList = organizationService.findOrgTreeDtosByUser(companyNo);
		return "orgTreeDtoList";
	}
	/**
	 * 查找内部机构.
	 * 
	 * @return String
	 */
	public String findInner() {
		if (parentOrgNo == null || parentOrgNo == 0) {
			orgTreeDtoList = organizationService.findInnerOrgTreeDtos();
			return "orgTreeDtoList";
		} else {
			orgTreeDtoList = organizationService.findSubOrgTreeDtos(parentOrgNo);
			return "orgTreeDtoList";
		}

	}

	/**
	 * 查找服务机构(树结构)
	 * 
	 * @return String
	 */
	public String findServicesTree() {
		if (parentOrgNo == null || parentOrgNo == 0) {
			orgTreeDtoList = organizationService.findServicesOrgTreeDtos();
			return "orgTreeDtoList";
		} else {
			orgTreeDtoList = organizationService.findSubOrgTreeDtos(parentOrgNo);
			return "orgTreeDtoList";
		}
	}

	/**
	 * 根据类型查找机构.
	 * 
	 * @return organization dto list
	 */
	public String findOrganizationsByType() {
		orgList = organizationService.findOrganizationsByType(orgNo, orgType);
		return "orgList";
	}

	/**
	 * find all Organization.
	 * 
	 * @return String result
	 */
	public String findAllCompany() {
		orgTreeDtoList = organizationService.findOrganizationSelectTree();

		return "orgTreeDtoList";
	}

	/**
	 * 保存机构.
	 * 
	 * @return String
	 */
	public String save() {
		if ("inner".equals(actionType)) {
			organizationInnerService.saveOrganizationInner(organizationDto);
		}
		if ("services".equals(actionType)) {
			organizationServicesService.saveOrganizationServices(organizationDto);
		}

		return SUCCESS;
	}

	/**
	 * 修改机构.
	 * 
	 * @return String
	 */
	public String updateOrg() {
		if ("inner".equals(orgType)) {
			organizationInnerService.mergeOrganizationInner(organizationDto);
		}

		if ("services".equals(orgType)) {
			organizationServicesService.mergeOrganizationServices(organizationDto);
		}

		if ("company".equals(orgType) || "itsop".equals(orgType)) {
			if (companyNo != null) {

				organizationDto.setOrgNo(companyNo);
			}
			companyService.mergeCompany(organizationDto);
		}

		return SUCCESS;
	}

	/**
	 * 修改机构.
	 * 
	 * @return String
	 */
	public String updateOrgWin() {
		if ("inner".equals(actionType)) {
			organizationInnerService.mergeOrganizationInner(organizationDto);
		}else if ("services".equals(actionType)) {
			organizationServicesService.mergeOrganizationServices(organizationDto);
		}else if ("company".equals(actionType) || "itsop".equals(actionType)) {
			companyService.mergeCompany(organizationDto);
		}
		return SUCCESS;
	}

	/**
	 * 根据编号删除机构.
	 * 
	 * @return String
	 */
	public String remove() {
		try {
			organizationService.removeServicesOrg(orgNo);
			effect = "1";
		} catch (Exception ex) {
			effect = "0";
		}
		return "result";
	}

	/**
	 * 批量删除机构.
	 * 
	 * @return String
	 */
	public String deleteOrgs() {
		try {
			organizationService.deleteOrgs(orgNos);
		} catch (Exception ex) {
			StringWriter sw = new StringWriter();
			PrintWriter pw = new PrintWriter(sw);
			ex.printStackTrace(pw);
			if(sw.toString().contains("foreign key")){
				msg="error";
				return "msg";
			}else
			throw new ApplicationException("ERROR_DATA_CAN_NOT_DELETE", ex);
		}
		return SUCCESS;
	}

	/**
	 * 移动（修改父节点）
	 * 
	 * @return String
	 */
	public String moveOrg() {
		organizationService.moveOrg(organizationDto);
		return SUCCESS;
	}

	/**
	 * 复制机构.
	 * 
	 * @return String
	 */
	public String copyOrg() {
		orgNo = organizationService.copyOrg(organizationDto);
		return SUCCESS;
	}

	/**
	 * 保存公司信息.
	 * 
	 * @return String
	 */
	public String mergeCompany() {
		//操作用户必须属于要修改的公司才允许操作；
		Long cpNo = (Long)appctx.getAttribute("companyNo");
		if(cpNo.equals(companyNo)){
			if (companyNo != null) {
				organizationDto.setOrgNo(companyNo);
			}
			companyService.mergeCompany(organizationDto);
			appctx.setAttribute("companyNo", companyNo);
			appctx.setAttribute("companyName", organizationDto.getOrgName());
		}
		
		return SUCCESS;
	}

	/**
	 * 根据orgNo获取ortDto
	 * 
	 * @return String
	 */
	public String getOrgByOrgNo() {
		organizationDto = organizationService.findOrganizationById(orgNo);
		return "organizationDto";
	}

	/**
	 * 根据编号获得角色列表
	 * 
	 * @return String
	 */
	public String findRolesByOrgNo() {
		orgRoles = organizationService.findRolesByOrgNo(orgNo);
		return "orgRoles";
	}

	/**
	 * 导出CSV.
	 * 
	 * @return inputStream
	 */
	public String exportOrganization() {
		if (companyNo != null) {
			organizationQueryDto.setCompanyNo(companyNo);
		}
		organizationQueryDto.setStart(0);
		organizationQueryDto.setLimit(10000);
		exportFile = organizationService.exportOrganization(organizationQueryDto);
		return "exportFile";

	}

	/**
	 * 导入CSV
	 * 
	 * @return import result
	 */
	public String importOrganization() {
		effect = organizationService.importOrganization(importFile.getAbsolutePath());
		return "result";
	}

	/**
	 * 获取外包服务商公司
	 * 
	 * @return Organization
	 */
	public String findServiceProvidersCompany() {
		organizationDto = organizationService.findServiceProvidersCompany();
		return "organizationDto";
	}

	/**
	 * 根据类型查找机构.数组id
	 * 
	 * @return organization dto list
	 */
	public String findOrganizationsByTypeArray() {
		orgList = organizationService.findOrganizationsByTypeArray(orgNos, orgTypes);
		return "orgList";
	}
	
	public String isCategoryExisted() {
		organizationDto.setOrgType(actionType);
        boolean con = organizationService.isCategoryExisted(organizationDto);
        msg = con ? "isExist" : "";
        return "msg";
    }
    
    /**
      * 判断编辑时分类是否存在
      */
    public String isCategoryExistdOnEdit() {
    	organizationDto.setOrgType(actionType);
        boolean con = organizationService.isCategoryExistdOnEdit(organizationDto);
        msg = con ? "isExist" : "";
        return "msg";
    }
}
